package com.mm.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mm.entity.MmUser;
import com.mm.service.impl.MmUserServiceImpl;
import com.mm.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Slf4j
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    MmUserServiceImpl userService;


    /**
     * 重写 Realm 的 supports() 方法是通过 JWT 进行登录判断的关键
     * 因为前文中创建了 JWTToken 用于替换 Shiro 原生 token
     * 所以必须在此方法中显式的进行替换，否则在进行判断时会一直失败
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可
     *
     * @param auth
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException{
        log.info("————身份认证方法————");
        String token = (String) auth.getPrincipal();
        if (token == null) {
            throw new AuthenticationException("token非法无效!");
        }
        String userName = JwtUtil.getUsername(token);
        LambdaQueryWrapper<MmUser> lambda = new QueryWrapper<MmUser>().lambda();
        MmUser user = userService.getOne(lambda.eq(MmUser::getUsername,userName));
        if (user == null) {
            throw new UnknownAccountException(ResultCodeEnum.NO_USERNAME.getMessage());
        }
        if (!JwtUtil.verify(token, userName, user.getPassword())) {
            throw new AuthenticationException(ResultCodeEnum.USERNAME_ERROR.getMessage());
        }
        return new SimpleAuthenticationInfo(user, token, getName());
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("————权限认证————");
        MmUser user = (MmUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 设置用户拥有的权限集合，比如“sys:role:add,sys:user:add”
      /*  Set<String> userPermissionByUserId = userService.getBaseMapper().getUserPermissionByUserId(user.getId());
        info.setStringPermissions(userPermissionByUserId);*/
        // 设置用户拥有的角色集合，比如“admin,test”
      /*  Set<String> roleSet = commonAPI.queryUserRoles(username);
        System.out.println(roleSet.toString());
        info.setRoles(roleSet);
        */

        return info;
    }
}
